package org.jsola.hr.service.impl;

import com.alibaba.excel.write.handler.CellWriteHandler;
import org.jsola.common.CollectionKit;
import org.jsola.common.StrKit;
import org.jsola.core.Page;
import org.jsola.exception.ParamException;
import org.jsola.hr.common.ExampleKit;
import org.jsola.hr.common.ExcelKit;
import org.jsola.hr.common.RegUtils;
import org.jsola.hr.common.oneKeyPay.AliGetUserInfo;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.constant.TransferAccountsPayStatusEnum;
import org.jsola.hr.constant.TransferAccountsSubjectStatusEnum;
import org.jsola.hr.constant.TransferAccountsTypeEnum;
import org.jsola.hr.dao.ITransferAccountsPeopleDAO;
import org.jsola.hr.dto.TransferAccountsDetailAddDTO;
import org.jsola.hr.dto.TransferAccountsPeopleAddDTO;
import org.jsola.hr.dto.TransferAccountsPeopleH5AddDTO;
import org.jsola.hr.dto.TransferAccountsPeopleUpdateDTO;
import org.jsola.hr.entity.TransferAccountsBatchDO;
import org.jsola.hr.entity.TransferAccountsDetailDO;
import org.jsola.hr.entity.TransferAccountsPeopleDO;
import org.jsola.hr.query.TransferAccountsPeopleQuery;
import org.jsola.hr.service.ITransferAccountInfoService;
import org.jsola.hr.service.ITransferAccountsBatchService;
import org.jsola.hr.service.ITransferAccountsDetailService;
import org.jsola.hr.service.ITransferAccountsPeopleService;
import org.jsola.hr.vo.TransferAccountsPeopleListVO;
import org.jsola.hr.vo.TransferAccountsPeoplePasteVO;
import org.jsola.hr.vo.TransferAccountsPeopleVO;
import org.jsola.hr.vo.payWx.VxWgkUserAuthResultVO;
import org.jsola.user.core.TokenUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 转账人员库
 *
 * @author zhr
 */
@Service("hrTransferAccountsPeopleServiceImpl")
public class TransferAccountsPeopleServiceImpl implements ITransferAccountsPeopleService {

    @Autowired
    private ITransferAccountsPeopleDAO transferAccountsPeopleDAO;
    @Autowired
    private ITransferAccountsBatchService transferAccountsBatchService;
    @Autowired
    private ITransferAccountsDetailService transferAccountsDetailService;
    @Autowired
    private ITransferAccountInfoService transferAccountInfoService;

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public TransferAccountsPeopleVO save(TransferAccountsPeopleAddDTO transferAccountsPeopleAddDTO, TokenUser tokenUser) {
        // 转DO
        TransferAccountsPeopleDO transferAccountsPeopleDO = transferAccountsPeopleAddDTO.to(TransferAccountsPeopleDO.class);
        // 校验格式
        checkPeople(transferAccountsPeopleDO, tokenUser);
        // 设置初始值
        if (transferAccountsPeopleDO.getIsVxBinding() == null) {
            transferAccountsPeopleDO.setIsVxBinding(false);
        }
        // 保存
        transferAccountsPeopleDO = save(transferAccountsPeopleDO, tokenUser.getSiteId(), tokenUser.getUserId());
        return transferAccountsPeopleDO.to(TransferAccountsPeopleVO.class);
    }

    private void checkPeople(TransferAccountsPeopleDO transferAccountsPeopleDO, TokenUser tokenUser) {
        if (StrKit.isEmpty(transferAccountsPeopleDO.getIdCard())) {
            throw new ParamException("身份证号不能为空！");
        }
        if (tokenUser != null) {
            // 校验身份证号是否重复
            ParamException.isNull(this.selectByIdCard(transferAccountsPeopleDO.getIdCard(), tokenUser.getSiteId()),
                    "身份证号在人员库已存在，不允许重复添加!");
        }
        if (StrKit.isNotEmpty(transferAccountsPeopleDO.getPhone())) {
            if (!RegUtils.isMobile(transferAccountsPeopleDO.getPhone())) {
                throw new ParamException("手机号格式不对！");
            }
        }
        // 校验身份证号格式
        if (!RegUtils.isIdCard(transferAccountsPeopleDO.getIdCard())) {
            throw new ParamException("身份证号格式不对！");
        }
        // 校验支付宝账号格式
        if (StrKit.isNotEmpty(transferAccountsPeopleDO.getZfbIdentity())) {
            if (!RegUtils.isMobile(transferAccountsPeopleDO.getZfbIdentity())
                    && !RegUtils.isEmail(transferAccountsPeopleDO.getZfbIdentity())) {
                throw new ParamException("支付宝账号格式不对！（支付宝登录账号：邮箱或手机号）");
            }
        }
        // 校验银行卡号
        if (StrKit.isNotEmpty(transferAccountsPeopleDO.getBankIdentity())) {
            if (!RegUtils.isBankCard(transferAccountsPeopleDO.getBankIdentity())) {
                throw new ParamException("银行卡号格式不对");
            }
        }
        // 识别开户行
        String bankName = transferAccountsPeopleDO.getOpeningBank();
        if (StrKit.isEmpty(bankName) && StrKit.isNotEmpty(transferAccountsPeopleDO.getBankIdentity())) {
            bankName = AliGetUserInfo.bankNameByBankNo(transferAccountsPeopleDO.getBankIdentity());
            bankName = AliGetUserInfo.bankNameToChinese(bankName);
        }
        transferAccountsPeopleDO.setOpeningBank(bankName);

    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int update(TransferAccountsPeopleUpdateDTO transferAccountsPeopleUpdateDTO, TokenUser tokenUser) {
        //转DO
        TransferAccountsPeopleDO transferAccountsPeopleDO = transferAccountsPeopleUpdateDTO.to(TransferAccountsPeopleDO.class);
        // 处理业务逻辑
        checkPeople(transferAccountsPeopleDO, null);
        this.updatePeopleLogic(transferAccountsPeopleDO, tokenUser);
        //根据主键更新，只更新非null值
        return updateByIdSelective(transferAccountsPeopleDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int updateDO(TransferAccountsPeopleDO transferAccountsPeopleDO, TokenUser tokenUser) {
        this.updatePeopleLogic(transferAccountsPeopleDO, tokenUser);
        return updateByIdSelective(transferAccountsPeopleDO, tokenUser.getSiteId(), tokenUser.getUserId());
    }

    private void updatePeopleLogic(TransferAccountsPeopleDO transferAccountsPeopleDO, TokenUser tokenUser) {
        // 修改人员库数据时需要同步批次明细里面的数据(只修改申请中的明细)
        List<TransferAccountsDetailDO> transferAccountsDetailDOList = transferAccountsDetailService
                .selectByPeopleIdAndSubjectStatus(transferAccountsPeopleDO.getId(),
                        TransferAccountsSubjectStatusEnum.WAIT_APPLICATION.getValue(), tokenUser.getSiteId());
        if (CollectionUtils.isEmpty(transferAccountsDetailDOList)) {
            return;
        }
        for (TransferAccountsDetailDO transferAccountsDetailDO : transferAccountsDetailDOList) {
            String identity;
            if (TransferAccountsTypeEnum.ZFB.getValue().equals(transferAccountsDetailDO.getType())) {
                identity = transferAccountsPeopleDO.getZfbIdentity();
            } else if (TransferAccountsTypeEnum.VX.getValue().equals(transferAccountsDetailDO.getType())) {
                identity = transferAccountsPeopleDO.getVxIdentity();
                transferAccountsDetailDO.setIdentityBinding(transferAccountsPeopleDO.getIsVxBinding());
            } else {
                identity = transferAccountsPeopleDO.getBankIdentity();
            }
            transferAccountsDetailDO.setPhone(transferAccountsPeopleDO.getPhone());
            transferAccountsDetailDO.setIdentity(identity);
            transferAccountsDetailDO.setName(transferAccountsPeopleDO.getName());
            transferAccountsDetailService.updateByIdSelective(transferAccountsDetailDO);
        }
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int deleteByIds(TokenUser tokenUser, String... transferAccountsPeopleIds) {
        for (String transferAccountsPeopleId : transferAccountsPeopleIds) {
            // 删除人员库数据时需要同步批次明细里面的数据(只删除申请中的明细)
            List<TransferAccountsDetailDO> transferAccountsDetailDOList = transferAccountsDetailService
                    .selectByPeopleIdAndSubjectStatus(transferAccountsPeopleId,
                            TransferAccountsSubjectStatusEnum.WAIT_APPLICATION.getValue(), tokenUser.getSiteId());
            if (CollectionUtils.isEmpty(transferAccountsDetailDOList)) {
                continue;
            }
            for (TransferAccountsDetailDO transferAccountsDetailDO : transferAccountsDetailDOList) {
                transferAccountsDetailService.deleteByIds(tokenUser, transferAccountsDetailDO.getId());
            }
        }
        return logicalDeleteByIds(tokenUser.getSiteId(), tokenUser.getUserId(), (Object[]) transferAccountsPeopleIds);
    }


    @Override
    public TransferAccountsPeopleVO selectById(String transferAccountsPeopleId, String siteId) {
        TransferAccountsPeopleDO transferAccountsPeopleDO = selectDOById(transferAccountsPeopleId, siteId);
        if (transferAccountsPeopleDO == null) {
            return null;
        }
        return transferAccountsPeopleDO.to(TransferAccountsPeopleVO.class);
    }

    @Override
    public List<TransferAccountsPeopleListVO> select(TransferAccountsPeopleQuery transferAccountsPeopleQuery, String siteId) {
        List<TransferAccountsPeopleDO> transferAccountsPeopleDOList = selectDO(transferAccountsPeopleQuery, siteId);
        if(CollectionUtils.isEmpty(transferAccountsPeopleDOList)) {
            return transferAccountsPeopleDOList == null ? null : new ArrayList<>();
        }
        return transferAccountsPeopleDOList.stream()
                .map(transferAccountsPeopleDO -> transferAccountsPeopleDO.to(TransferAccountsPeopleListVO.class))
                .collect(Collectors.toList());
    }

    @Override
    public int selectCount(TransferAccountsPeopleQuery transferAccountsPeopleQuery, String siteId) {
        Example example = buildExample(transferAccountsPeopleQuery,siteId);
        return transferAccountsPeopleDAO.selectCountByExample(example);
    }

    @Override
    public Page<TransferAccountsPeopleListVO> selectPage(TransferAccountsPeopleQuery transferAccountsPeopleQuery, String siteId) {
        Example example = buildExample(transferAccountsPeopleQuery,siteId);
        Page<TransferAccountsPeopleDO> page = transferAccountsPeopleDAO.selectPageByExample(example,
                transferAccountsPeopleQuery.getPageNo(),
                transferAccountsPeopleQuery.getPageSize());

        return page.to(TransferAccountsPeopleListVO.class);
    }

    @Override
    public TransferAccountsPeopleDO selectDOById(String transferAccountsPeopleId, String siteId) {
        return listById(transferAccountsPeopleId, siteId);
    }

    @Override
    public List<TransferAccountsPeopleDO> selectDO(TransferAccountsPeopleQuery transferAccountsPeopleQuery, String siteId) {
        Example example = buildExample(transferAccountsPeopleQuery,siteId);
        return transferAccountsPeopleDAO.selectByExample(example);
    }

    @Override
    public TransferAccountsPeopleDO selectByCompanyIdAndIdCard(String companyId, String idCard, String siteId) {
        if (StrKit.isEmpty(idCard) || StrKit.isEmpty(siteId)) {
            return null;
        }
        Example example = new Example(TransferAccountsPeopleDO.class);
        example.and()
                .andEqualTo("companyId", companyId)
                .andEqualTo("idCard", idCard)
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        return transferAccountsPeopleDAO.selectOneByExample(example);
    }

    @Override
    public TransferAccountsPeopleDO selectByIdCard(String idCard, String siteId) {
        if (StrKit.isEmpty(idCard) || StrKit.isEmpty(siteId)) {
            return null;
        }
        Example example = new Example(TransferAccountsPeopleDO.class);
        example.and()
                .andEqualTo("idCard", idCard)
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        return transferAccountsPeopleDAO.selectOneByExample(example);
    }

    @Override
    @Transactional(value = HrConstants.TX, rollbackFor = Exception.class)
    public int h5SaveData(TransferAccountsPeopleH5AddDTO transferAccountsPeopleH5AddDTO) {
        String name = transferAccountsPeopleH5AddDTO.getName();
        String nickName = transferAccountsPeopleH5AddDTO.getNickName();
        String idCard = transferAccountsPeopleH5AddDTO.getIdCard();
        String phone = transferAccountsPeopleH5AddDTO.getPhone();
        String zfbIdentity = transferAccountsPeopleH5AddDTO.getZfbIdentity();
        String unionId = transferAccountsPeopleH5AddDTO.getUnionId();
        String openId = transferAccountsPeopleH5AddDTO.getOpenId();
        String batchId = transferAccountsPeopleH5AddDTO.getBatchId();
        String siteId = transferAccountsPeopleH5AddDTO.getSiteId();
        String avatar = transferAccountsPeopleH5AddDTO.getAvatar();
        String openingBank = transferAccountsPeopleH5AddDTO.getOpeningBank();
        String bankCard = transferAccountsPeopleH5AddDTO.getBankCard();
        if (StrKit.isNotEmpty(bankCard)) {
            bankCard = bankCard.replaceAll(" ", "");
            if (StrKit.isEmpty(openingBank)) {
                openingBank = AliGetUserInfo.bankNameByBankNo(bankCard);
                openingBank = AliGetUserInfo.bankNameToChinese(openingBank);
            }
        }
        String idCardUrl = transferAccountsPeopleH5AddDTO.getIdCardUrl();
        String bankCardUrl = transferAccountsPeopleH5AddDTO.getBankCardUrl();
        if (StrKit.isEmpty(name)) {
            throw new ParamException("姓名未填写");
        }
        if (StrKit.isEmpty(idCard)) {
            throw new ParamException("身份证号未填写");
        }
//        if (StrKit.isEmpty(openId)) {
//            throw new ParamException("微信授权取消，添加失败！");
//        }
        if (StrKit.isEmpty(siteId)) {
            throw new ParamException("站点为空，请重新生成二维码！");
        }
        // 校验身份证号格式
        if (!RegUtils.isIdCard(idCard)) {
            throw new ParamException("身份证号格式不对");
        }
        // 校验手机号格式
        if (StrKit.isNotEmpty(phone)) {
            if (!RegUtils.isMobile(phone)) {
                throw new ParamException("手机号格式不对");
            }
        }
        // 校验支付宝账号格式
        if (StrKit.isNotEmpty(zfbIdentity)) {
            if (!RegUtils.isMobile(zfbIdentity) && !RegUtils.isEmail(zfbIdentity)) {
                throw new ParamException("支付宝账号格式不对(支付宝登录账号————手机号或邮箱)");
            }
        }
        // 校验银行卡号
        if (StrKit.isNotEmpty(bankCard)) {
            if (!RegUtils.isBankCard(bankCard)) {
                throw new ParamException("银行卡号格式不对");
            }
        }
        TokenUser tokenUser = new TokenUser("system", siteId);
        // 保存信息到人员库
        TransferAccountsPeopleDO transferAccountsPeopleDO = this.savePeople(avatar, name, nickName, phone, zfbIdentity,
                bankCard, openingBank, bankCardUrl, openId, idCard, idCardUrl, siteId);
        // 没有批次id  直接返回
        if (StrKit.isEmpty(batchId)) {
            return 1;
        }
        // 查询批次明细
        List<TransferAccountsDetailDO> transferAccountsDetailDOList = transferAccountsDetailService
                .selectByBatchId(batchId, tokenUser.getSiteId());
        List<String> existPhones = transferAccountsDetailDOList.stream().map(TransferAccountsDetailDO::getPhone)
                .collect(Collectors.toList());
        List<String> existIdentitys = transferAccountsDetailDOList.stream().map(TransferAccountsDetailDO::getIdentity)
                .collect(Collectors.toList());
        // 有批次id需要添加到明细中 或 修改明细
        this.saveDetailToBatch(batchId, siteId, zfbIdentity, bankCard, openingBank, idCard, phone, name, openId,
                transferAccountsPeopleDO.getId(), existPhones, existIdentitys, tokenUser);
        return 1;
    }

    @Override
    public List<TransferAccountsPeopleDO> selectBySiteId(String siteId) {
        if (StrKit.isEmpty(siteId)) {
            throw new ParamException("租户id不能为空!");
        }
        Example example = new Example(TransferAccountsPeopleDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        return transferAccountsPeopleDAO.selectByExample(example);
    }

    private void saveDetailToBatch(String batchId, String siteId, String zfbIdentity, String bankCard, String openingBank,
                                   String idCard, String phone, String name, String openId, String peopleId,
                                   List<String> existPhones, List<String> existIdentitys, TokenUser tokenUser) {
        // 查询批次信息
        TransferAccountsBatchDO transferAccountsBatchDO = transferAccountsBatchService.selectDOById(batchId, siteId);
        ParamException.notNull(transferAccountsBatchDO, "批次信息不存在或已删除，请刷新重试");
        if (TransferAccountsTypeEnum.ZFB.getValue().equals(transferAccountsBatchDO.getType())
                && StrKit.isEmpty(zfbIdentity)) {
            throw new ParamException("发放方式为支付宝时支付宝账号必填!");
        } else if (TransferAccountsTypeEnum.VX.getValue().equals(transferAccountsBatchDO.getType())) {
            if (StrKit.isEmpty(openId)) {
                throw new ParamException("发放方式为微工卡时必须微工卡授权!");
            }
            // 查询微工卡授权状态
            VxWgkUserAuthResultVO vxWgkUserAuthResultVO = transferAccountInfoService
                    .selectUserAuthStatus(openId, siteId);
            if (vxWgkUserAuthResultVO == null ||
                    !"AUTHORIZED".equals(vxWgkUserAuthResultVO.getAuthorizeState())) {
                throw new ParamException("发放方式为微工卡时必须微工卡授权!");
            }
        } else if (TransferAccountsTypeEnum.BANK.getValue().equals(transferAccountsBatchDO.getType())
                && StrKit.isEmpty(bankCard)) {
            throw new ParamException("发放方式为银行时银行卡号必填!");
        }
        if (!TransferAccountsSubjectStatusEnum.WAIT_APPLICATION.getValue().equals(transferAccountsBatchDO.getSubjectStatus())) {
            throw new ParamException("批次状态不是待申请，不能添加人员！");
        }
        // 查询批次信息的人员信息
        TransferAccountsDetailDO transferAccountsDetailDO = transferAccountsDetailService
                .selectByBatchIdAndIdCard(batchId, idCard, siteId);
        if (transferAccountsDetailDO == null) {
            // 判断是否有手机号重复
            if (StrKit.isNotEmpty(phone) && existPhones.contains(phone)) {
                throw new ParamException("手机号在批次明细中已存在");
            }
            // 新增批次明细信息
            List<TransferAccountsDetailAddDTO> transferAccountsDetailAddDTOList = new ArrayList<>();
            TransferAccountsDetailAddDTO transferAccountsDetailAddDTO = new TransferAccountsDetailAddDTO();
            transferAccountsDetailAddDTO.setType(transferAccountsBatchDO.getType());
            transferAccountsDetailAddDTO.setBatchId(batchId);
            transferAccountsDetailAddDTO.setPayStatus(TransferAccountsPayStatusEnum.NO_PAY.getValue());
            transferAccountsDetailAddDTO.setSubjectStatus(TransferAccountsSubjectStatusEnum.WAIT_APPLICATION.getValue());
            transferAccountsDetailAddDTO.setPhone(phone);
            transferAccountsDetailAddDTO.setCompanyId(transferAccountsBatchDO.getCompanyId());
            transferAccountsDetailAddDTO.setPeopleId(peopleId);
            transferAccountsDetailAddDTO.setName(name);
            transferAccountsDetailAddDTO.setIdCard(idCard);
            if (TransferAccountsTypeEnum.ZFB.getValue().equals(transferAccountsBatchDO.getType())) {
                if (existIdentitys.contains(zfbIdentity)) {
                    throw new ParamException("支付宝账号在批次明细中已存在");
                }
                transferAccountsDetailAddDTO.setIdentity(zfbIdentity);
            } else if (TransferAccountsTypeEnum.VX.getValue().equals(transferAccountsBatchDO.getType())) {
                if (existIdentitys.contains(openId)) {
                    throw new ParamException("微信发放账号在批次明细中已存在");
                }
                transferAccountsDetailAddDTO.setIdentity(openId);
                transferAccountsDetailAddDTO.setIdentityBinding(true);
            } else if (TransferAccountsTypeEnum.BANK.getValue().equals(transferAccountsBatchDO.getType())) {
                if (existIdentitys.contains(bankCard)) {
                    throw new ParamException("银行卡账号在批次明细中已存在");
                }
                transferAccountsDetailAddDTO.setIdentity(bankCard);
                transferAccountsDetailAddDTO.setIsPingAnBank(openingBank.contains("平安银行"));
                transferAccountsDetailAddDTO.setBankName(openingBank);
            }
            transferAccountsDetailAddDTOList.add(transferAccountsDetailAddDTO);
            transferAccountsDetailService.saveBatch(transferAccountsDetailAddDTOList, tokenUser);
            return;
        } else {
            throw new ParamException("该身份证信息对应的明细已存在，请删除后重试！");
        }
        // 修改明细信息
//        TransferAccountsDetailUpdateDTO transferAccountsDetailUpdateDTO = new TransferAccountsDetailUpdateDTO();
//        transferAccountsDetailUpdateDTO.setId(transferAccountsDetailDO.getId());
//        transferAccountsDetailUpdateDTO.setName(name);
//        if (StrKit.isNotEmpty(phone)) {
//            transferAccountsDetailUpdateDTO.setPhone(phone);
//        }
//        if (TransferAccountsTypeEnum.ZFB.getValue().equals(transferAccountsBatchDO.getType())) {
//            transferAccountsDetailUpdateDTO.setIdentity(zfbIdentity);
//        } else if (TransferAccountsTypeEnum.VX.getValue().equals(transferAccountsBatchDO.getType())) {
//            transferAccountsDetailUpdateDTO.setIdentity(openId);
//        }
//        transferAccountsDetailService.update(transferAccountsDetailUpdateDTO, tokenUser);
    }

    /**
     * 保存或者修改人员库信息
     * @param avatar 头像
     * @param name 姓名
     * @param nickName 微信昵称
     * @param phone 电话
     * @param zfbIdentity 支付宝账号
     * @param bankCard 银行卡号
     * @param openingBank 银行开户行
     * @param bankCardUrl 银行卡文件地址
     * @param openId openId
     * @param idCard 身份证号
     * @param idCardUrl 身份证文件地址
     * @param siteId 租户id
     * @return 人员库信息
     */
    private TransferAccountsPeopleDO savePeople(String avatar, String name, String nickName, String phone,
                                                String zfbIdentity, String bankCard, String openingBank,
                                                String bankCardUrl, String openId, String idCard,
                                                String idCardUrl, String siteId) {
        TransferAccountsPeopleDO transferAccountsPeopleDO = this.selectByIdCard(idCard, siteId);
        boolean isAuthVx = false;
        if (StrKit.isNotEmpty(openId)) {
            // 查询微工卡授权状态
            VxWgkUserAuthResultVO vxWgkUserAuthResultVO = transferAccountInfoService
                    .selectUserAuthStatus(openId, siteId);
            if (vxWgkUserAuthResultVO != null &&
                    "AUTHORIZED".equals(vxWgkUserAuthResultVO.getAuthorizeState())) {
                isAuthVx = true;
            }
        }
        if (transferAccountsPeopleDO != null) {
            // 校验是否允许修改
            String error = this.checkUpdate(transferAccountsPeopleDO, name, phone, zfbIdentity, bankCard, openingBank);
            if (StrKit.isNotEmpty(error)) {
                throw new ParamException(error);
            }
            // 更新人员库
            transferAccountsPeopleDO.setName(name);
            if (StrKit.isNotEmpty(phone)) {
                transferAccountsPeopleDO.setPhone(phone);
            }
            transferAccountsPeopleDO.setAvatar(avatar);
            transferAccountsPeopleDO.setNickName(nickName);
            transferAccountsPeopleDO.setZfbIdentity(zfbIdentity);
            transferAccountsPeopleDO.setIdCardUrl(idCardUrl);
            transferAccountsPeopleDO.setBankIdentity(bankCard);
            transferAccountsPeopleDO.setOpeningBank(openingBank);
            transferAccountsPeopleDO.setBankCardUrl(bankCardUrl);
            transferAccountsPeopleDO.setVxIdentity(openId);
            transferAccountsPeopleDO.setIsVxBinding(isAuthVx);
            this.updateDO(transferAccountsPeopleDO, new TokenUser("systemUpdate", siteId));
        } else {
            // 新增人员库信息
            transferAccountsPeopleDO = new TransferAccountsPeopleDO();
            transferAccountsPeopleDO.setName(name);
            transferAccountsPeopleDO.setNickName(nickName);
            transferAccountsPeopleDO.setIdCard(idCard);
            transferAccountsPeopleDO.setPhone(phone);
            transferAccountsPeopleDO.setAvatar(avatar);
            transferAccountsPeopleDO.setZfbIdentity(zfbIdentity);
            transferAccountsPeopleDO.setBankIdentity(bankCard);
            transferAccountsPeopleDO.setOpeningBank(openingBank);
            transferAccountsPeopleDO.setBankCardUrl(bankCardUrl);
            transferAccountsPeopleDO.setIdCardUrl(idCardUrl);
            transferAccountsPeopleDO.setVxIdentity(openId);
            transferAccountsPeopleDO.setIsVxBinding(isAuthVx);
            transferAccountsPeopleDO = save(transferAccountsPeopleDO, siteId, "system");
        }
        return transferAccountsPeopleDO;
    }

    @Override
    public String checkUpdate(TransferAccountsPeopleDO transferAccountsPeopleDO,
                              String name, String phone, String zfbIdentity,
                              String bankCard, String bankName) {
        if (StrKit.isNotEmpty(transferAccountsPeopleDO.getPhone()) && StrKit.isNotEmpty(phone)) {
            if (!phone.equals(transferAccountsPeopleDO.getPhone())) {
                return "姓名：" + name + "的人员库中该身份证信息对应的手机号和此次录入手机号不同，添加失败！";
            }
        }
        if (StrKit.isNotEmpty(transferAccountsPeopleDO.getZfbIdentity()) && StrKit.isNotEmpty(zfbIdentity)) {
            if (!zfbIdentity.equals(transferAccountsPeopleDO.getZfbIdentity())) {
                return "姓名：" + name + "的人员库中该身份证信息对应的支付宝账号和此次录入支付宝账号不同，添加失败！";
            }
        }
        if (StrKit.isNotEmpty(transferAccountsPeopleDO.getBankIdentity()) && StrKit.isNotEmpty(bankCard)) {
            if (!bankCard.equals(transferAccountsPeopleDO.getBankIdentity())) {
                return "姓名：" + name + "的人员库中该身份证信息对应的银行卡账号和此次录入银行卡账号不同，添加失败！";
            }
        }
        if (StrKit.isNotEmpty(transferAccountsPeopleDO.getOpeningBank()) && StrKit.isNotEmpty(bankName)) {
            if (!bankName.equals(transferAccountsPeopleDO.getOpeningBank())) {
                return "姓名：" + name + "的人员库中该身份证信息对应的银行卡名称和此次录入银行卡名称不同，添加失败！";
            }
        }
        if (StrKit.isNotEmpty(transferAccountsPeopleDO.getName()) && StrKit.isNotEmpty(name)) {
            if (!name.equals(transferAccountsPeopleDO.getName())) {
                return "姓名：" + name + "的人员库中该身份证信息对应的姓名和此次录入姓名不同，添加失败！";
            }
        }
        return null;

    }

    @Override
    public String exportTransferAccountsPeopleList(TransferAccountsPeopleQuery transferAccountsPeopleQuery, TokenUser tokenUser) {
        // 查询转账人员库信息 先根据ids查询
        List<TransferAccountsPeopleDO> transferAccountsPeopleDOList;
        Example example = buildExample(transferAccountsPeopleQuery, tokenUser.getSiteId());
        if (CollectionKit.isNotEmpty(transferAccountsPeopleQuery.getIdList())) {
            example = new Example(TransferAccountsPeopleDO.class);
            example.and()
                    .andEqualTo("valid", true)
                    .andEqualTo("siteId", tokenUser.getSiteId())
                    .andIn("id", transferAccountsPeopleQuery.getIdList());
        }
        transferAccountsPeopleDOList = transferAccountsPeopleDAO.selectByExample(example);
        ParamException.notEmpty(transferAccountsPeopleDOList, "没有需要导出的数据，请检查检索条件");
        // 数据
        List<List<String>> dataList = new ArrayList<>();
        // 表头
        List<List<String>> headList = new ArrayList<>();
        String[] headArray = {"姓名", "身份证号", "手机号", "支付宝账号","微信openId", "银行卡号", "银行名称"};
        for (String headItem : headArray) {
            List<String> head = new ArrayList<>();
            head.add(headItem);
            headList.add(head);
        }
        for (TransferAccountsPeopleDO data : transferAccountsPeopleDOList) {
            List<String> oneDate = new ArrayList<>();
            oneDate.add(data.getName());
            oneDate.add(data.getIdCard());
            oneDate.add(data.getPhone());
            oneDate.add(data.getZfbIdentity());
            oneDate.add(data.getVxIdentity());
            oneDate.add(data.getBankIdentity());
            oneDate.add(data.getOpeningBank());
            dataList.add(oneDate);
        }
        return ExcelKit.writeExcelWithModel("转账人员信息", dataList, headList, false, null,
                (CellWriteHandler) null);
    }

    @Override
    public TransferAccountsPeoplePasteVO selectByIdCards(TransferAccountsPeopleQuery transferAccountsPeopleQuery, TokenUser tokenUser) {
        List<String> idCardList = transferAccountsPeopleQuery.getIdCardsList();
        TransferAccountsPeoplePasteVO transferAccountsPeoplePasteVO = new TransferAccountsPeoplePasteVO();
        if (CollectionUtils.isEmpty(idCardList)) {
            return transferAccountsPeoplePasteVO;
        }
        Example example = new Example(TransferAccountsPeopleDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", tokenUser.getSiteId())
                .andIn("idCard", idCardList);
        List<TransferAccountsPeopleDO> transferAccountsPeopleDOList = transferAccountsPeopleDAO.selectByExample(example);
        if (CollectionUtils.isEmpty(transferAccountsPeopleDOList)) {
            transferAccountsPeoplePasteVO.setIdCardList(idCardList);
            return transferAccountsPeoplePasteVO;
        }
        List<TransferAccountsPeopleVO> transferAccountsPeopleVOList = transferAccountsPeopleDOList.stream()
                .map(transferAccountsPeopleDO -> transferAccountsPeopleDO.to(TransferAccountsPeopleVO.class))
                .collect(Collectors.toList());
        // 过滤查询到的身份证号
        idCardList.removeAll(transferAccountsPeopleVOList.stream()
                .map(TransferAccountsPeopleVO::getIdCard).collect(Collectors.toList()));
        transferAccountsPeoplePasteVO.setIdCardList(idCardList);
        transferAccountsPeoplePasteVO.setTransferAccountsPeopleVOList(transferAccountsPeopleVOList);
        return transferAccountsPeoplePasteVO;
    }


    /**
     * 根据查询参数，构建example

     * @param transferAccountsPeopleQuery 查询参数
     * @param siteId 所属站点id
     * @return example
     */
    private Example buildExample(TransferAccountsPeopleQuery transferAccountsPeopleQuery, String siteId) {
        Example example = new Example(TransferAccountsPeopleDO.class);
        example.and()
                .andEqualTo("valid", true)
                .andEqualTo("siteId", siteId);
        if (transferAccountsPeopleQuery.getCompanyId() != null) {
            example.and().andEqualTo("companyId", transferAccountsPeopleQuery.getCompanyId());
        }
        if (transferAccountsPeopleQuery.getPhone() != null) {
            example.and().andLike("phone", "%" + transferAccountsPeopleQuery.getPhone() + "%");
        }
        if (transferAccountsPeopleQuery.getName() != null) {
            example.and().andLike("name", "%" + transferAccountsPeopleQuery.getName() + "%");
        }
        if (transferAccountsPeopleQuery.getIdCard() != null) {
            example.and().andLike("idCard", "%" + transferAccountsPeopleQuery.getIdCard() + "%");
        }
        if (transferAccountsPeopleQuery.getIsZfbBinding() != null) {
            example.and().andEqualTo("isZfbBinding", transferAccountsPeopleQuery.getIsZfbBinding());
        }
        if (transferAccountsPeopleQuery.getIsVxBinding() != null) {
            example.and().andEqualTo("isVxBinding", transferAccountsPeopleQuery.getIsVxBinding());
        }
        if (transferAccountsPeopleQuery.getIsBankBinding() != null) {
            example.and().andEqualTo("isBankBinding", transferAccountsPeopleQuery.getIsBankBinding());
        }
        if (StrKit.isNotEmpty(transferAccountsPeopleQuery.getNameOrPhoneOrIdCard())) {
            example.and()
                    .orLike("name", "%" + transferAccountsPeopleQuery.getNameOrPhoneOrIdCard() + "%")
                    .orLike("idCard", "%" + transferAccountsPeopleQuery.getNameOrPhoneOrIdCard() + "%")
                    .orLike("phone", "%" + transferAccountsPeopleQuery.getNameOrPhoneOrIdCard() + "%");
        }
        // 排序
        ExampleKit.setExampleOrder(example,transferAccountsPeopleQuery.getOrders());
        return example;
    }
}




